from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from core.browse_simulator import BrowseSimulator
from selenium.common.exceptions import TimeoutException
from urllib.parse import quote
import json
import time
import os
import datetime
import random
import requests
import re
import secrets
import html  

class WechatWorkAlert:
    def __init__(self, webhook_url):
        self.webhook_url = webhook_url
        self.headers = {'Content-Type': 'application/json'}


    def send_message(self, message):
        """发送验证码出现警报"""
        payload = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"{message}",
                "mentioned_list": ["@all"]
            }
        }
        
        try:
            response = requests.post(
                self.webhook_url,
                headers=self.headers,
                data=json.dumps(payload),
                timeout=10
            )
            return response.json().get("errcode") == 0
        except Exception as e:
            print(f"企业微信通知发送失败: {str(e)}")
            return False

    def send_qrcode(self, qrcodeimgurl, user_id):
        """发送微博登录二维码"""
        payload = {
            "msgtype": "markdown",
            "markdown": {
                "content": 
                    f"<font color=\"warning\">微博二维码登录</font>\n"
                    f"用户ID:<font color=\"info\"> {user_id}</font>\n"
                    f"打开二维码图片并使用新浪微博扫描："
                    f"[二维码链接]({qrcodeimgurl})\n"
                    f"（二维码10分钟内有效）\n"
                    f"时间：{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"                    
                ,
                "mentioned_list": ["@all"]
            }
        }        
        try:
            response = requests.post(
                self.webhook_url,
                headers=self.headers,
                data=json.dumps(payload),
                timeout=10
            )
            return response.json().get("errcode") == 0
        except Exception as e:
            print(f"企业微信通知发送失败: {str(e)}")
            return False

class WeiboAutoReposter:
    def __init__(self):

        self.wechat_alert = WechatWorkAlert(
            webhook_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ffd42d15-f025-48a5-adb9-5b9089ccf971"
        )
        self.callback_base = "http://wbhook.xawb.cn:8901/captcha_callback"
        self.api_base = "http://wbhook.xawb.cn:8901/"
        self.api_timeout = 30
        self.verification = 0 # 验证码状态
        self.verification_count = 0 # 验证码尝试次数
        self.target_user = "大皖新闻"  # 目标用户名
        self.api_url = "https://api.siliconflow.cn/v1/chat/completions"
        self.api_key = "sk-nbnpftafdbxqfttaedidmqpwevinkvixnucpudanuykywflx"
        self.max_retries = 3
        self.current_user_id = None
        self.current_opration = None
        self.midcount = 0
        # 从文件加载历史记录
        self.processed_mids = set()
        if os.path.exists("processed.log"):
            with open("processed.log", "r") as f:
                self.processed_mids = set(f.read().splitlines())
        
        # 新增最后mid记录属性
        self.last_processed_mid1 = None  # 最后处理的mid
        self.last_processed_mid2 = None  # 最后处理的mid       
        self.scroll_retries = 10        # 最大滚动重试次数
        self.scroll_step = 500         # 滚动步长(px)
        # 修改初始化加载逻辑
        if os.path.exists("processed.log"):
            with open("processed.log", "r") as f:
                # 获取最后一行有效mid
                lines = [line.strip() for line in f if line.strip()]
                if lines:
                    self.last_processed_mid1 = lines[-1]
                    self.last_processed_mid2 = lines[-2]
                    print(f"最后处理的MID: {self.last_processed_mid1}")

        # 可继续添加更多微博表情符号...
        self.emoji_library = [
            "[微笑]", "[哈哈]", "[太开心]", "[鼓掌]", "[好喜欢]",
            "[心]", "[鲜花]", "[礼物]", "[给力]", "[围观]",
            "[赞]", "[奥特曼]", "[威武]", "[浮云]", "[月亮]","支持",
        ]

        self.last_mid = None  # 最后转发的微博ID
        self.cookie_file = "weibo_cookies.json"



    # 通过api获取回调URL
    def _generate_callback_url(self):

        try:
            response = requests.post(
                f"{self.api_base}/api/generate_callback",
                json={
                    "user_id": self.current_user_id,
                    "callback_base": self.callback_base
                },
                timeout=5
            )
            result = response.json()
            
            if result['status'] != 'success':
                raise RuntimeError(f"API Error: {result.get('message')}")
                
            return result['callback_url']
        except Exception as e:
            print(f"⚠️ 回调URL生成失败: {str(e)}")
            raise
    
    def send_captcha_alert(self, user_id,current_opration):
        """发送带处理链接的企业微信通知"""
        callback_url = self._generate_callback_url()
        message = (
            f"⚠️<font color=\"warning\">{current_opration}操作检测到验证码弹窗</font>\n"
            f"用户ID:<font color=\"info\"> {user_id}</font>\n"
            f"请按以下步骤处理：\n"
            f"1. 点赞、评论、转发和点赞别人的评论手动完成验证码\n"
            f"2. 点击确认链接: [确认验证完成]({callback_url})\n"
            f"（链接2小时内有效）"
            f"\n时间：{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
        )
        self.wechat_alert.send_message(message)
    
    def _check_resolution_status(self):
        """检查服务端验证码解决状态"""
        try:
            url = f"{self.callback_base}/status?user_id={self.current_user_id}"
            response = requests.get(url, timeout=self.api_timeout)
            return response.json().get('resolved', False)
        except Exception as e:
            print(f"状态检查失败: {str(e)}")
            return False
    
    def handle_captcha(self, opration):
        """改造后的验证码处理流程"""
        if not self._check_captcha_popup():
            return True
            
        print("⚠️操作检测到验证码弹窗，发送处理通知...")
        self.send_captcha_alert(self.current_user_id, opration)
        
        # 等待用户处理（轮询检查）
        start_time = time.time()
        while time.time() - start_time < 18000:  # 5小时超时
            if self._check_resolution_status():
                print("✅ 用户已处理验证码")
                self.driver.refresh()
                return True
            time.sleep(30)  # 每60秒检查一次
            
        print("❌ 验证码未及时处理")
        raise RuntimeError("验证码处理超时")
    def save_cookies(self):
        """增强版Cookie保存"""
        # 获取所有Cookie（包括HttpOnly）
        cookies = self.driver.get_cookies()
        
        # 特别保存关键Cookie
        essential_cookies = ['SUB', 'SUBP', 'SSOLoginState']
        filtered_cookies = [c for c in cookies if c['name'] in essential_cookies]
        
        # 添加过期时间（延长7天）
        for cookie in filtered_cookies:
            if 'expiry' not in cookie:
                cookie['expiry'] = int(time.time()) + 604800
        
        with open(self.cookie_file, 'w') as f:
            json.dump(filtered_cookies, f)
        
        print(f"✅ 已保存{len(filtered_cookies)}个关键Cookie")
    
    def _safe_extract(self, response_data):
        """安全提取生成内容"""
        try:
            return response_data["choices"][0]["message"]["content"].strip()
        except (KeyError, IndexError) as e:
            raise ValueError(f"响应解析失败: {str(e)}")
        
    def ai_generate(self, weibo_content):
        """执行评论生成"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        for attempt in range(self.max_retries):
            try:
                response = requests.post(
                    self.api_url,
                    json=self._generate_payload(weibo_content),
                    headers=headers,
                    timeout=60
                )
                response.raise_for_status()
                return self._safe_extract(response.json())
                
            except requests.exceptions.RequestException as e:
                if attempt == self.max_retries - 1:
                    raise Exception(f"API请求失败: {str(e)}")
                time.sleep(2 ** attempt)
                
        return None

    def _generate_payload(self, weibo_content):
        """构造API请求参数"""
        return {
            "model": "Qwen/Qwen2.5-7B-Instruct",
            "stream": False,
            "max_tokens": 512,
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "messages": [{
                "role": "user",
                "content": f"对以下微博内容生成一条2-5字的简短评论（要求口语化）：{weibo_content}"
            }],
        }

    # 配置浏览器选项
    def _init_driver(self):
     
        current_dir = os.path.dirname(os.path.abspath(__file__))
        options = Options()
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        options.add_argument('--no-sandbox')  # 禁用沙箱
        options.add_argument('--disable-dev-shm-usage')  # 禁用共享内存
        options.add_argument('--force-device-scale-factor=1')
        # 重要：启用Cookie持久化
        options.add_argument(f"user-data-dir={os.path.abspath('chrome_profile')}")
        chrome_dir = os.path.join(current_dir, "chrome")
        options.binary_location =os.path.join(chrome_dir, "chrome.exe")
        driver_path = os.path.join(current_dir, "drivers", "chromedriver.exe")
        service = Service(
            executable_path=driver_path,
            port=random.randint(10000, 65535)
            )
        driver = webdriver.Chrome(service=service, options=options)
        return driver

    def get_topic(self, text: str) -> str:
        """
        精准提取文本中第一个完整的话题标签
        参数：
            text (str): 需要解析的文本内容
        返回：
            str: 提取到的第一个话题内容（不带#号），若无合法话题返回空字符串
        """
        pattern = r'(?<!\\)#((?:[^#\\]|\\.)+?)#'

        match = re.search(pattern, text, flags=re.DOTALL)
        return match.group(0) if match else ''

    def load_cookies(self):
        self.driver.get("https://weibo.com")
        with open(self.cookie_file, 'r') as f:
            cookies = json.load(f)
            for cookie in cookies:
                self.driver.add_cookie(cookie)
        self.driver.refresh()

    def manual_login(self):
        """交互式登录流程"""
        print("🔑 请手动登录微博...")

        while True:
            try:        
                self.driver.get("https://passport.weibo.com/sso/signin?entry=account&source=sinassopage&url=https%3A%2F%2Fweibo.com")

                # 精准定位二维码元素
                qr_img = WebDriverWait(self.driver, 20).until(
                    EC.presence_of_element_located((By.XPATH, 
                        '//div[contains(@class,"relative")]//img[contains(@src,"qr.weibo.cn")]'
                    ))
                )

                # 直接提取src属性
                qr_url = html.unescape(qr_img.get_attribute('src'))
                print(f"🔗 解析到动态二维码链接: {qr_url[:300]}")
                self.wechat_alert.send_qrcode(qr_url,self.current_user_id)
                        
            except Exception as e:
                print(f"⚠️ 二维码发送失败: {str(e)}")
            
            for attempt in range(30):
                time.sleep(60) # 每60秒检查一次
                # 登录状态检测
                if self._check_login_status():
                    print("✅ 登录成功")
                    # 登录后获取关键Cookie
                    self._capture_sensitive_cookies()
                    self.save_cookies()
                        # 读取用户名
                    profile_div = WebDriverWait(self.driver, 5).until(
                        EC.presence_of_element_located((
                            By.XPATH,
                            '//div[contains(@class, "Ctrls_item") '
                            'and contains(@class, "Ctrls_avatarItem") '
                            'and @title]'
                        ))
                    )           
                    self.current_user_id = profile_div.get_attribute("title")   
                    return
            print("⏳ 等待30分钟后重试...")

                
    
    def _capture_sensitive_cookies(self):
        """通过CDP获取敏感Cookie"""
        try:
            cookies = self.driver.execute_cdp_cmd('Network.getAllCookies', {})
            sensitive_cookies = [
                {'name': c['name'], 'value': c['value'], 'domain': c['domain']}
                for c in cookies['cookies'] 
                if c['name'] in ['SUB', 'SUBP']
            ]
            with open('sensitive_cookies.json', 'w') as f:
                json.dump(sensitive_cookies, f)
        except Exception as e:
            print(f"⚠️ 无法获取敏感Cookie: {str(e)}")

    def _check_login_status(self):
        """
        Check multiple conditions to verify login status on Weibo.
        
        Returns:
            bool: True if all login checks pass, False otherwise.
            
        Checks performed:
        - Current URL is not on passport.weibo.com
        - "Private Message" element exists on page
        - Login box element is not present
        """
        """多重验证登录状态"""
        checks = [
            lambda: 'passport.weibo.com' not in self.driver.current_url,
            lambda: self.driver.find_elements(By.XPATH, '//*[contains(text(),"私信")]'),
            lambda: not self.driver.find_elements(By.CSS_SELECTOR, '.loginbox')
        ]
        return all(check() for check in checks)
    
    def login_with_cookies(self):
        """增强版Cookie登录"""
        try:
            with open(self.cookie_file, 'r') as f:
                cookies = json.load(f)
            
            self.driver.get("https://weibo.com")
            time.sleep(2)
            
            # 分步加载Cookie
            for cookie in cookies:
                # 修复域名问题
                if 'weibo.com' not in cookie.get('domain', ''):
                    cookie['domain'] = '.weibo.com'
                
                try:
                    self.driver.add_cookie(cookie)
                except Exception as e:
                    print(f"⚠️ 加载Cookie失败: {cookie['name']} - {str(e)}")
            
            # 验证登录状态
            self.driver.refresh()
            time.sleep(3)
            
            if not self._check_login_status():
                raise Exception("Cookie登录状态验证失败")
            
            print("✅ Cookie自动登录成功")

            # 读取用户名
            profile_div = WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((
                    By.XPATH,
                    '//div[contains(@class, "Ctrls_item") '
                    'and contains(@class, "Ctrls_avatarItem") '
                    'and @title]'
                ))
            )           
            self.current_user_id = profile_div.get_attribute("title")
            return True
            
        except Exception as e:
            print(f"❌ Cookie登录失败: {str(e)},请手动登录")
            return False

    def _locate_mid_element(self, mid1, mid2):
        """精准定位MID元素"""
        print(f"开始定位MID: {mid1}, {mid2}")
        try:
            # 优先直接定位
            element = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((
                    By.XPATH, 
                    f'//a[contains(@href, "/{mid1}") or contains(@href, "/{mid2}")]'
                ))
            )
            self._smart_scroll_to(element)
            return element
        except TimeoutException:
            print("元素未找到，启动动态滚动定位...")
            return self._scroll_to_find_mid(mid1,mid2)

    def _scroll_to_find_mid(self, mid1,mid2):
        """滚动查找MID元素"""
        last_height = self.driver.execute_script("return document.body.scrollHeight")
        retry_count = 0
        
        while retry_count < self.scroll_retries:
            # 执行差异化滚动
            self.driver.execute_script(f"window.scrollBy(0, {self.scroll_step})")
            time.sleep(1.5)  # 模拟人工滚动间隔
            
            # 尝试查找元素
            elements = self.driver.find_elements(By.XPATH, f'//a[contains(@href, "/{mid1}") or contains(@href, "/{mid2}")]')
            if elements:
                print("✅滚动定位成功")
                return elements[0]
            
            # 检测是否到达底部
            new_height = self.driver.execute_script("return document.body.scrollHeight")
            if new_height == last_height:
                retry_count += 1
                print(f"触底重试 {retry_count}/{self.scroll_retries}")
            else:
                last_height = new_height
                
        print("达到最大重试次数仍未找到")
        return None
    def _smart_scroll_to(self, element):
        """智能滚动到元素可见区域"""
        self.driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})", element)
        # 补偿顶部导航栏高度
        self.driver.execute_script("window.scrollBy(0, -60)")
        time.sleep(0.5)  # 等待滚动完成

    def get_target_weibo(self):
        from datetime import datetime
        # 跳转到目标用户主页
        self.driver.get(f"https://weibo.com/n/{self.target_user}")
        weibo_list =  []
        time.sleep(2)

        # 新增验证码检测
        if not self.handle_captcha("点击大皖新闻首页"):
            raise RuntimeError("验证码处理失败")

        """增量处理新稿件"""
        if self.last_processed_mid1:
            # 定位到最后位置并处理后续
            anchor_element = self._locate_mid_element(self.last_processed_mid1,self.last_processed_mid2)
            if anchor_element or self.scroll_retries :
                print("✅定位成功，开始处理后续稿件...")    
                try:               
                    # 等待主容器加载
                    #WebDriverWait(self.driver, 15).until(
                    #    EC.presence_of_element_located((By.XPATH, '//div[@class="container"]//div[contains(@class,"wbpro-scroller-item") and @data-index]'))
                    #)

                    # 精准定位
                    self.driver.execute_script("window.scrollBy(0, 300);")
                    time.sleep(1.5)
                    weibo_list = self.driver.find_elements(By.XPATH, '//div[@class="container"]//div[contains(@class,"vue-recycle-scroller__item-view")]')
                    print(f"✅获取到 {len(weibo_list)} 条微博")
                    sorted_weibo = []
                    error_count = 0

                    for weibo in weibo_list:
                        try:
                            weibo_link = weibo.find_element(By.XPATH, './/a[contains(@href, "weibo.com/")]')
                            href = weibo_link.get_attribute("href")
                            time_detail = weibo_link.get_attribute("title")
                            dt = datetime.strptime(time_detail, "%Y-%m-%d %H:%M")
                            sorted_weibo.append( (dt, weibo) )
                        except Exception as e:
                            error_count += 1
                            print(f"❌时间解析失败，使用最低优先级 | 错误：{str(e)}")
                            sorted_weibo.append( (datetime.min, weibo) )  # 错误条目排最后

                    # 第二步：降序排序（最新在前）
                    sorted_weibo.sort(key=lambda x: x[0], reverse=True)
                    
                    # 第三步：重组排序后的列表
                    weibo_list = [weibo for dt, weibo in sorted_weibo]

                    # 输出排序结果
                    print(f"排序完成 | 有效条目：{len(weibo_list)-error_count} | 错误条目：{error_count}")

                    # 调试输出（展示排序后结果）
                    for i, weibo in enumerate(weibo_list):
                        try:
                            weibo_link = weibo.find_element(By.XPATH, './/a[contains(@href, "weibo.com/")]')  # 与之前相同的定位逻辑
                            time_detail = weibo_link.get_attribute("title")
                            href = weibo_link.get_attribute("href")
                            print(f"排序后索引 {i} → 时间：{time_detail}，链接：{href}")
                        except:
                            print(f"排序后索引 {i} → 信息缺失")

                    return weibo_list
                
                except Exception as e:
                    print("❌元素定位失败:", str(e))
                    return []                    

                    return weibo_list
                
                except Exception as e:
                    print("❌元素定位失败:", str(e))
                    return []

    def generate_dynamic_comment(self, content_text):
        """支持运行时调整比例"""
        # 可配置的权重字典
        weights = {
            'topic': 70,   # 50%
            'hybrid': 20   # 20%
        }
        
        # 按权重随机选择
        choice = random.choices(
            population=['topic', 'hybrid'],
            weights=[weights['topic'], weights['hybrid']],
            k=1
        )[0]

        if choice == 'topic':
            return self.get_topic(content_text)
        else:
            topic = self.get_topic(content_text)
            ai = self.ai_generate(content_text)
            return f"{topic} {ai}"[:50]  # 限制长度

    def _check_captcha_popup(self):
        """检测极验验证框"""

        # 定义双重检测条件
        conditions = [
            (By.XPATH, '//div[contains(@class,"geetest_box")]'),  # 极验验证框
            (By.XPATH, '//div[contains(@class,"woo-dialog-title")]')  # 优化后的表达式
        ]
        try:
            # 使用any_of组合检测条件
            WebDriverWait(self.driver, 10).until(
                EC.any_of(
                    EC.visibility_of_element_located(conditions[0]),
                    EC.visibility_of_element_located(conditions[1])
                )
            )
            self.verification = 1
            self.verification_count += 1
            return True
        except TimeoutException:
            return False
        except Exception as e:
            print(f"验证检测异常: {e}")
            return False

    def is_userid_present(self, driver, container, userid, timeout=10):  
        """根据USERID检测评论是否成功"""
        try:
            WebDriverWait(driver, timeout).until(  # 使用传入的driver
                EC.visibility_of_element_located(
                    (By.XPATH, f'.//a[contains(text(),"{userid}")]')
                )
            )
            return True
        except TimeoutException:
            return False

    def repost_weibo(self, weibo_item, comment_id):

        comment_text =""
        try:
            # 定位comment_id元素
            weibo_href = WebDriverWait(weibo_item, 20).until(
                EC.presence_of_element_located((By.XPATH, f'.//a[contains(@href, "/{comment_id}")]'))
            )

            data_index = weibo_href.find_element(By.XPATH, 
                "./ancestor::div[contains(@class,'wbpro-scroller-item') and @data-index]"
            )
            
            # 调试：打印原始位置
            rect_before = self.driver.execute_script("""
                return arguments[0].getBoundingClientRect();
            """, data_index)
            print(f"滚动前位置: top={rect_before['top']}, 视口高度={self.driver.execute_script('return window.innerHeight')}")

            time.sleep(3)  # 等待滚动动画
            # 执行增强滚动
            self.driver.execute_script("""
                const el = arguments[0];
                // 补偿值（根据实际导航栏高度调整）
                const offset = 50;  
                
                // 计算精确位置
                const targetY = el.getBoundingClientRect().top + window.pageYOffset - offset;
                
                // 分阶段滚动
                el.scrollIntoView({behavior: 'auto', block: 'center'});
                window.scrollTo({
                    top: targetY,
                    behavior: 'smooth'
                });
                
                // 调试标记
                el.style.boxShadow = "0 0 0 3px red";
            """, data_index)
            # 强制等待滚动完成
            time.sleep(1.5)  # 微博页面需要更长的稳定时间

            # 验证结果
            time.sleep(1)  # 等待滚动动画
            rect_after = self.driver.execute_script("""
                return arguments[0].getBoundingClientRect();
            """, data_index)
            print(f"滚动后位置: top={rect_after['top']}")
            
            # 如果仍然不可见，尝试紧急方案
            if rect_after['top'] < 0 :
                self.driver.execute_script("window.scrollBy(0, arguments[0].getBoundingClientRect().top - 100);", data_index)
 
            time.sleep(random.uniform(5.5, 10.8))
            content_element = weibo_item.find_element(By.XPATH, './/div[@class="wbpro-feed-content"]')

            # 生成评论
            comment_text = self.generate_dynamic_comment(content_element.text) 
            print("生成评论内容:", comment_text)
            if not comment_text or len(comment_text) < 2:
                comment_text = "转发微博" 
        
            # 改用更稳健的定位方式定位转发按钮
            repost_btn = WebDriverWait(weibo_item, 10).until(
                lambda x: x.find_element(By.XPATH, './/*[contains(@title,"转发")][not(ancestor::div[contains(@class,"retweet")])]')
            )

            # 改用更稳健的定位方式定位评论按钮
            comment_btn = WebDriverWait(weibo_item, 10).until(
                lambda x: x.find_element(By.XPATH, './/*[contains(@title,"评论")][not(ancestor::div[contains(@class,"retweet")])]')
            )            

            # 确保元素可交互
            self.driver.execute_script("""
                arguments[0].scrollIntoView({block: 'center'});
                arguments[0].style.zIndex = "9999";
            """, comment_btn)

            # 点赞
            dianzan_btn = WebDriverWait(weibo_item, 10).until(
                lambda x: x.find_element(By.XPATH, './/button[@title="赞"][not(ancestor::div[contains(@class,"retweet")])]')
            )
            # 确保元素可交互
            self.driver.execute_script("""
                arguments[0].scrollIntoView({block: 'center'});
                arguments[0].style.zIndex = "9999";
            """, dianzan_btn)

            ActionChains(self.driver).move_to_element(dianzan_btn).pause(2).click().perform()

            # 新增验证码检测
            if not self.handle_captcha("点赞"):
                raise RuntimeError("验证码处理失败")
            print("✅点赞成功")

            time.sleep(random.uniform(2.5, 4.8))

            # 使用ActionChains模拟人类操作
            ActionChains(self.driver).move_to_element(comment_btn).pause(2).click().perform()
            print("点击评论按钮")
            time.sleep(random.uniform(2, 4))           

        except Exception as e:
            print("❌评论转发失败:", str(e))
            return False

        # 评论和评论点赞操作
        try:
            # 显式等待评论区域加载
            WebDriverWait(weibo_item, 15).until(
                EC.presence_of_element_located((By.XPATH, './/div[contains(@class, "Feed_box")]'))
            )
            
            # 定位到具体的评论容器（新增）
            comment_container = weibo_item.find_element(By.XPATH, './/div[contains(@class, "Feed_box")]')

            if self.verification_count <= 1:
                # 等待评论框出现（作用域限定在容器内）
                WebDriverWait(weibo_item, 15).until(
                    EC.presence_of_element_located((By.XPATH, './/textarea[@placeholder="发布你的评论"]'))
                )
                
                # 输入评论内容（增加清除原有内容步骤）
                text_area = weibo_item.find_element(By.XPATH, './/textarea[@placeholder="发布你的评论"]')
                text_area.clear()
                for char in comment_text:
                    text_area.send_keys(char)
                    time.sleep(0.05)  # 模拟人类输入速度
                text_area.send_keys(Keys.SPACE)
                print("输入评论内容") 
                
                # 提交评论（优化等待条件）
                comfpost_btn = WebDriverWait(weibo_item, 10).until(
                    EC.element_to_be_clickable((By.XPATH, './/button[.//span[text()="评论"]]'))
                )
                ActionChains(self.driver).move_to_element(comfpost_btn).pause(1.5).click().perform()

                # 点击评论后，检查是否成功
                if not self.handle_captcha("评论"):
                    raise RuntimeError("验证码处理失败")

                if self.is_userid_present(
                    driver=self.driver,
                    container=comment_container,
                    userid=self.current_user_id
                ):
                    print(f"✅评论成功")
            
            time.sleep(random.uniform(1.2, 3.3))

            # 点赞和回复操作（限定在评论容器内,第一条稿件评论）
            
            if self.midcount == 1:
                try:
                    like_btns = comment_container.find_elements(By.XPATH, './/button[@title="赞"]')
                    comments_comment_btns = comment_container.find_elements(By.XPATH, './/i[@title="评论"]')
                    
                    # 仅给第二个点赞
                    if len(like_btns) >= 2:

                        # 精确获取第二个点赞按钮（索引为1）
                        second_like_btn = like_btns[1]  
                        
                        # 添加滚动确保可见性
                        self.driver.execute_script("arguments[0].scrollIntoViewIfNeeded()", second_like_btn)
                        
                        # 带视觉停留的高级点击
                        ActionChains(self.driver).move_to_element(second_like_btn).pause(0.8)\
                            .move_by_offset(2, -2).pause(0.3)\
                            .click().pause(0.5)\
                            .perform()
                        
                        if not self.handle_captcha("评论点赞"):
                            raise RuntimeError("验证码处理失败")
                            
                        print("✅成功点赞第二条评论")
                    
                    # 给第二个评论回复
                    if len(comments_comment_btns) >= 2:

                        # 精确获取第二个点赞按钮（索引为1）
                        second_coment_btn = comments_comment_btns[1]  
                        
                        # 添加滚动确保可见性
                        self.driver.execute_script("arguments[0].scrollIntoViewIfNeeded()", second_coment_btn)
                        
                        # 带视觉停留的高级点击
                        ActionChains(self.driver).move_to_element(second_coment_btn).pause(0.8)\
                            .move_by_offset(2, -2).pause(0.3)\
                            .click().pause(0.5)\
                            .perform()
                        
                        time.sleep(random.uniform(2.2, 3.3))
                        # 显式等待评论区域加载
                        WebDriverWait(self.driver, 15).until(
                            EC.presence_of_element_located((By.XPATH, '//div[contains(@class, "wbpro-layer")]'))
                        )
                        
                        # 定位到具体的评论容器（新增）
                        comment_container = self.driver.find_element(By.XPATH, '//div[contains(@class, "wbpro-layer")]')
                        
                        # 等待评论框出现（作用域限定在容器内）
                        WebDriverWait(self.driver, 15).until(
                            EC.presence_of_element_located((By.XPATH, '//textarea[@placeholder="发布你的回复"]'))
                        )
                        
                        # 输入转发内容（增加清除原有内容步骤）

                        # 生成评论
                        senond_comment_text = self.ai_generate(content_element.text)
                        print("生成评论内容:", senond_comment_text)
                        if not senond_comment_text or len(senond_comment_text) < 2:
                            senond_comment_text = random.choice(self.emoji_library)

                        text_area = self.driver.find_element(By.XPATH, '//textarea[@placeholder="发布你的回复"]')
                        text_area.clear()
                        for char in senond_comment_text:
                            text_area.send_keys(char)
                            time.sleep(0.05)  # 模拟人类输入速度
                        text_area.send_keys(Keys.SPACE)
                        print(f"输入回复内容{senond_comment_text}") 
                        
                        time.sleep(random.uniform(2.2, 3.3))
                        # 提交评论（优化等待条件）
                        second_comfpost_btn = WebDriverWait(self.driver, 10).until(
                            EC.element_to_be_clickable((By.XPATH, '//button[.//span[text()="回复"]]'))
                        )

                        ActionChains(self.driver).move_to_element(second_comfpost_btn).pause(1.5).click().perform()

                        # 点击评论后，检查是否成功
                        if not self.handle_captcha("评论回复"):
                            raise RuntimeError("验证码处理失败")
                            
                        print("✅成功回复第二条评论")                    
                    
                except Exception as e:
                    print(f"❌评论处理失败: {str(e)}")
                    self.driver.save_screenshot('error.png')
                    return False

        except Exception as e:
            print("❌处理失败:", str(e))
            return False
        
        # 转发操作
        try:
            # 使用ActionChains模拟人类操作转发
            ActionChains(self.driver).move_to_element(repost_btn).pause(2).click().perform()
            print("点击转发按钮")
            time.sleep(random.uniform(2, 4))
            # 显式等待评论区域加载
            WebDriverWait(weibo_item, 15).until(
                EC.presence_of_element_located((By.XPATH, './/div[contains(@class, "Feed_box")]'))
            )
            
            # 定位到具体的评论容器
            comment_container = weibo_item.find_element(By.XPATH, './/div[contains(@class, "Feed_box")]')   

            # 提交转发
            try:
                comfrepost_btn = WebDriverWait(weibo_item, 10).until(
                    EC.element_to_be_clickable((By.XPATH, './/button[.//span[text()="转发"]]'))
                )
                ActionChains(self.driver).move_to_element(comfrepost_btn).pause(1.5).click().perform()
                
                if not self.handle_captcha("转发"):
                    raise RuntimeError("验证码处理失败")
                    
                print("✅转发成功")
                return True
            
            except Exception as e:
                print(f"❌转发失败: {str(e)}")
                self.driver.save_screenshot('error.png')
                return False
                          
        except Exception as e:
            print("❌转发失败:", str(e))
            self.driver.save_screenshot('error.png')
            return False
        
    def maintain_log_file(self):  # 添加self参数
        """维护日志文件的方法"""
        try:
            with open("processed.log", "r+") as f:
                lines = [line.strip() for line in f.readlines()]
                
                # 去重逻辑
                unique_lines = list(set(lines))
                
                # 保留最后300条
                if len(unique_lines) > 300:
                    unique_lines = unique_lines[-300:]
                
                f.seek(0)
                f.write("\n".join(unique_lines) + '\n')  
                f.truncate()
                
            print(f"日志已维护，当前记录数：{len(unique_lines)}")
        except FileNotFoundError:
            print("无历史日志文件")
    
    # 等待倒计时
    def countdown(self, t):
        """兼容性最好的倒计时"""
        print(f"倒计时: {t}秒")
        while t:
            mins, secs = divmod(t, 60)
            # 固定宽度避免残留
            timer = '[{:02d}:{:02d}]'.format(mins, secs).ljust(15)
            print(timer, end="\r", flush=True)
            time.sleep(1)
            t -= 1
        print("倒计时结束!".ljust(15))  # 清除最后一行

    def clear_memory(self):
        """定期清理浏览器内存"""
        self.driver.execute_script("""
            window.performance && window.performance.clearResourceTimings();
            if(window.gc) window.gc();
        """)
        print("内存垃圾已强制回收")

    def run(self):
        try:
            while True:
                # 凌晨减少检查频率
                hour = datetime.datetime.now().hour
                if 0 <= hour < 7 or 12 <= hour < 13 or 17 <= hour < 18 or hour > 23: 
                    if hasattr(self, 'driver') and self.driver:
                        self.driver.quit()
                        self.driver = None
                        # 清理残留进程
                        os.system("taskkill /f /im chrome.exe >nul 2>&1")
                        os.system("taskkill /f /im chromedriver.exe >nul 2>&1")
                        
                        # 清理无效会话文件
                        for f in ['chrome_profile/DevToolsActivePort', 'chrome_profile/LOCK']:
                            if os.path.exists(f):
                                os.remove(f)
                    print("🕒 暂停时段(23-8点，12-14点，17-19点)，浏览器已关闭")
                    time.sleep(3600)  # 10分钟检查一次
                    continue
                else:
                    check_interval = (660, 780) #12-14分钟处理一次

                #夜里重置验证码次数
                if 0 <= hour < 8:
                    self.verification_count = 0 

                # 非休息时段检查浏览器状态
                print(f"验证次数:{self.verification_count}")
                if not hasattr(self, 'driver') or not self.driver:
                    print("🕒 检查浏览器状态...")
                    self.driver = self._init_driver()  # 重新初始化浏览器
                    self.browse_simulator = BrowseSimulator(self.driver)
                    # 新增验证码检测
                    if not self.handle_captcha("打开微博"):
                        raise RuntimeError("验证码处理失败")
                    if not self.login_with_cookies():
                        print(f"⚠️{self.current_user_id}❌微博未登录...")
                        self.manual_login()
                    print("✅浏览器已启动")

                self.verification = 0                
                print("开始检查新微博...")
                if os.path.exists("processed.log"):
                    with open("processed.log", "r") as f:
                        # 获取最后一行有效mid
                        lines = [line.strip() for line in f if line.strip()]
                        if lines:
                            self.last_processed_mid1 = lines[-1]
                            self.last_processed_mid2 = lines[-2]
                            print(f"最后处理的MID: {self.last_processed_mid1}")                
                sorted_list = self.get_target_weibo()
                
                if sorted_list:
                    self.midcount = 0
                    # 逆序处理：从旧到新，避免重复处理最新微博
                    for weibo in reversed(sorted_list):
                        try:
                            # 更健壮的MID提取方式
                            weibo_link = weibo.find_element(By.XPATH, './/a[contains(@href, "weibo.com/")]')
                            href = weibo_link.get_attribute("href")
                            time_detail = weibo_link.get_attribute("title")
                            current_mid = href.split("/")[-1].split("?")[0]  # 处理带参数的URL
                        except Exception as e:
                            print(f"❌提取MID失败: {str(e)}")
                            continue  # 跳过无法处理的微博

                        # 微博转评赞操作
                        try:
                            if current_mid not in self.processed_mids:
                                print(f"发现未评论转发的新微博 {current_mid},发布时间：{time_detail}")
                                if self.repost_weibo(weibo, current_mid):                                 
                                    
                                    self.processed_mids.add(current_mid)
                                    print(f"✅{datetime.datetime.now()}成功记录已转发ID: {current_mid}")
                                    self.last_processed_mid = current_mid
                                    # 可选：写入日志文件
                                    with open("processed.log", "a") as f:
                                        f.write(f"\n{current_mid}") if os.stat("processed.log").st_size > 0 else f.write(current_mid)
                                        f.write("\n")  # 双保险
                                    self.midcount += 1
                                    if self.midcount >= 2:  # 达到2条立即停止
                                        print("已达本次最大处理量（2条）")
                                        break
                                    time.sleep(30)
                                else:
                                    print(f"❌跳过评论转发失败的微博: {current_mid},稍后重试")
                                    break

                            else:
                                print(f"⚠️微博ID: {current_mid}已处理...")
                                
                        except Exception as e:
                            print(f"❌执行异常: {str(e)}")

                        if self.verification == 1:
                            print("⚠️用户手工验证完成，20分钟后重新开始检查微博...")
                            time.sleep(1200)  # 20分钟
                            break
                else:
                    print("⚠️没有检测到新的微博")

                # 等待间隔10-15分钟                  
                wait_time=random.randint(*check_interval)
                print(f"剩余等待时间: {wait_time//60}分{wait_time%60}秒")
                print("-----------------------------------------------------------------")
                time.sleep(wait_time)
                
        finally:
            self.driver.quit()

if __name__ == "__main__":
    bot = WeiboAutoReposter()
    bot.run()
